package com.inter.controller.travis;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.inter.entity.agatewaytobeijing.JsonConstant;
import com.inter.entity.agatewaytobeijing.querydevice.beijing.response.ResponseQueryDevice;
import com.inter.entity.interentity.utils.UtilsInterfacesPackage;
import com.inter.entity.newinterentity.querydevicerealtime.request.RequestQueryDeviceRealTime;
import com.inter.entity.newinterentity.querydevicerealtime.request.RequestQueryDeviceRealTimeData;
import com.inter.entity.newinterentity.querydevicerealtime.request.RequestQueryDeviceRealTimeTradeData;
import com.inter.entity.newinterentity.querydevicerealtime.response.ResponseQueryDeviceRealTime;
import com.inter.entity.newinterentity.querydevicerealtime.response.ResponseQueryDeviceRealTimeData;
import com.inter.entity.newinterentity.querydevicerealtime.response.ResponseQueryDeviceRealTimeTradeData;
import com.inter.entity.newinterentity.querydevicerealtime.response.ResponseQueryDeviceRealTimeTradeDataPackageOrder;
import com.inter.service.PartnerProductPackageService;
import com.inter.service.PartnerService;
import com.inter.service.SequenceService;
import com.inter.service.agatewaytobeijing.GatewayToBeijingService;
import com.inter.utils.MD5;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 查询单一设备实时信息
 * 接入方可以通过调用该接口，查询某个设备信息，包括设备的基本信息、设备当前订购的套餐信息等
 * 普通的客户在使用 ：类似 Travis和 TCL
 * <p>
 * <p>
 * TurnToQueryDeviceRealTimeService queryDeviceRealTime = new TurnToQueryDeviceRealTimeService();
 * DeviceRealTimeInformation information = queryDeviceRealTime.queryDeviceRealTime(deviceId, secret, partnerCode);
 *
 * @author lm
 * @date 2018/12/29
 */
@RestController
@Api(description = "查询单一设备实时信息 ")
@Slf4j
public class QuerySingleDeviceRealTimeQiTaController {
    @Autowired
    private SequenceService sequenceService;
    @Autowired
    PartnerService partnerService;
    @Autowired
    PartnerProductPackageService partnerProductPackageService;
    @Autowired
    GatewayToBeijingService toBeijingService;

    @CrossOrigin
    @RequestMapping(value = "querySingleDeviceRealTime", produces = "application/json;charset=utf-8", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "查询单一设备实时信息 ", response = ResponseQueryDeviceRealTime.class)
    public String querySingleDeviceRealTime(@ApiParam @RequestBody RequestQueryDeviceRealTime requestQueryDeviceRealTime) {

        // 1，生成流水号
        String connSeqNo = sequenceService.getPackageTaskNo();
        // 2,生成当前时间戳
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String curtime = df.format(new Date());
        //3,定义要回复的内容
        String jsonString;
        UtilsInterfacesPackage utils = new UtilsInterfacesPackage();
        String requestStr = JSON.toJSONString(requestQueryDeviceRealTime);
        if (StringUtils.isBlank(requestStr)) {
            log.info("请求报文不合法:requestStr为空");
            jsonString = utils.dataWeiKong(connSeqNo, curtime);
            return jsonString;
        } else {
            log.info("【Travis查询设备实时信息】请求：" + requestStr);
            RequestQueryDeviceRealTime requestPackage = JSONArray.parseObject(requestStr, RequestQueryDeviceRealTime.class);
            String requestSign = requestPackage.getSign();
            if (requestPackage.getSign() == null) {
                log.info("请求报文不合法:sign为空");
                jsonString = utils.dataWeiKong(connSeqNo, curtime);
                return jsonString;
            } else {
                RequestQueryDeviceRealTimeData requestData = requestPackage.getData();
                if (requestPackage.getData() == null) {
                    log.info("请求报文不合法:data为空");
                    jsonString = utils.dataWeiKong(connSeqNo, curtime);
                    return jsonString;
                } else {
                    String partnerCode = requestData.getPartnerCode();
                    String partnerName = partnerProductPackageService.queryPartnerNameBypartnerCode(partnerCode);
                    String secret = partnerService.findSecretByPartnerCode(partnerCode);
                    /*logger.info("渠道名称：" + partnerName + ";密钥是：" + secret);*/
                    String ConnSeqNo = requestData.getConnSeqNo();
                    String tradeTime = requestData.getTradeTime();
                    String token = requestData.getToken();
                    String tradeType = requestData.getTradeType();
                    String lang = requestData.getLang();

                    if (StringUtils.isBlank(partnerCode) || StringUtils.isBlank(partnerName) || StringUtils.isBlank(secret) || StringUtils.isBlank(token) ||
                            StringUtils.isBlank(tradeType) || StringUtils.isBlank(lang) || requestData.getTradeData() == null) {
                        log.info("请求报文不合法:data参数不合法");
                        jsonString = utils.dataWeiKong(connSeqNo, curtime);
                        return jsonString;
                    } else {

                        RequestQueryDeviceRealTimeTradeData requestTradeData = requestData.getTradeData();
                        String deviceId = requestTradeData.getDeviceId();

                        if (StringUtils.isBlank(deviceId)) {
                            log.info("请求报文不合法:tradeData的值为null或者为空");
                            jsonString = utils.dataWeiKong(connSeqNo, curtime);
                            return jsonString;
                        } else {
                            // 将请求体json转成String
                            String str = JSON.toJSONString(requestData);
                            // 将Str拿去计算签名
                            String sign = utils.calculateSignature(str);
                            if (!requestSign.equalsIgnoreCase(sign)) {
                                log.info("签名验证失败！");
                                jsonString = utils.publicMessage(ConnSeqNo, partnerCode, tradeTime, token, tradeType);
                                return jsonString;
                            } else {
                                /* 2021-05-25：添加修改用3.0企业网关的接口进行查询： 查询设备*/
                                ResponseQueryDevice response = toBeijingService.queryDevice(deviceId, partnerCode, secret);
                                /*没有查到设备信息*/
                                if (null == response || null == response.getCode() || null == response.getData()) {
                                    ResponseQueryDeviceRealTimeData data = new ResponseQueryDeviceRealTimeData();
                                    data.setConnSeqNo(ConnSeqNo);
                                    data.setPartnerCode(partnerCode);
                                    data.setToken(token);
                                    data.setTradeType(tradeType);
                                    data.setTradeTime(curtime);
                                    data.setTradeRstCode(1200);
                                    data.setTradeRstMessage("The current device information was not queried;未查询到当前设备信息!");

                                    ResponseQueryDeviceRealTime deviceRealTime = new ResponseQueryDeviceRealTime();
                                    deviceRealTime.setData(data);
                                    deviceRealTime.setSign(MD5.calcMD5(JSON.toJSONString(data)));

                                    jsonString = JSON.toJSONString(deviceRealTime);
                                    log.info("响应报文：" + jsonString);
                                    return jsonString;
                                }
                                /*查询到的设备接口返回的结果不是成功*/
                                if (!JsonConstant.RET_CODE_0000.equals(response.getCode())) {
                                    ResponseQueryDeviceRealTimeData data = new ResponseQueryDeviceRealTimeData();
                                    data.setConnSeqNo(ConnSeqNo);
                                    data.setPartnerCode(partnerCode);
                                    data.setToken(token);
                                    data.setTradeType(tradeType);
                                    data.setTradeTime(curtime);
                                    data.setTradeRstCode(Integer.parseInt(response.getCode()));
                                    data.setTradeRstMessage(response.getMessage());

                                    ResponseQueryDeviceRealTime deviceRealTime = new ResponseQueryDeviceRealTime();
                                    deviceRealTime.setData(data);
                                    deviceRealTime.setSign(MD5.calcMD5(JSON.toJSONString(data)));
                                    // 返回给调用者的报文
                                    jsonString = JSON.toJSONString(deviceRealTime);
                                    log.info("响应报文：" + jsonString);
                                    return jsonString;
                                }

                                /*查询设备信息成功*/
                                ResponseQueryDeviceRealTimeTradeData tradeData = null;
                                ResponseQueryDeviceRealTimeTradeDataPackageOrder order = null;

                                /*有正在使用的订单的情况*/
                                if (null != response.getData().getPackage_order()) {
                                    order = new ResponseQueryDeviceRealTimeTradeDataPackageOrder();
                                    String packageCode = response.getData().getPackage_order().getPackageCode();
                                    String usageAttribute = partnerProductPackageService.queryUsageAttributeByCode(partnerCode, packageCode);
                                    String packageNameEN = partnerProductPackageService.queryNameEnByCode(partnerCode, packageCode);

                                    order.setOrderCode(response.getData().getPackage_order().getOrderCode());
                                    if (lang.equalsIgnoreCase("en")) {
                                        order.setPackageName(packageNameEN);
                                    } else {
                                        order.setPackageName(response.getData().getPackage_order().getPackageName());
                                    }
                                    order.setPackageCode(packageCode);
                                    order.setUsageAttribute(usageAttribute);
                                    order.setPackageType(response.getData().getPackage_order().getPackageType());
                                    order.setBuyType(response.getData().getPackage_order().getBuyType());
                                    order.setOrderPeriod(response.getData().getPackage_order().getOrderPeriod());
                                    order.setFlow(response.getData().getPackage_order().getFlow());
                                    order.setUsedFlow(response.getData().getPackage_order().getUsedFlow());
                                    order.setFlowUseRate(response.getData().getPackage_order().getFlowUseRate());
                                    order.setOrderUsedFlow(response.getData().getPackage_order().getOrderUsedFlow());
                                    order.setOrderDate(response.getData().getPackage_order().getOrderDate());
                                    order.setActiveDate(response.getData().getPackage_order().getActiveDate());
                                    order.setExpireDate(response.getData().getPackage_order().getExpireDate());
                                    order.setIsOrderRefuelingPackage(response.getData().getPackage_order().getIsOrderRefuelingPackage());
                                    order.setRefuelingPackage(null);
                                }

                                /*没有正在使用的订单的情况*/
                                tradeData = new ResponseQueryDeviceRealTimeTradeData();
                                tradeData.setDeviceId(response.getData().getDevice_id());
                                tradeData.setOtaFlag(response.getData().getOta_flag());
                                tradeData.setBipFlag(response.getData().getBip_flag());
                                tradeData.setLifecycle(response.getData().getLifecycle());
                                tradeData.setMultiImsiFlag(response.getData().getMultiImsi_flag());
                                tradeData.setLifecycleStartTime(response.getData().getLifecycle_start_time());
                                tradeData.setLifecycleEndTime(response.getData().getLifecycle_end_time());
                                tradeData.setLifecycleSlientPeriod(response.getData().getLifecycle_slient_period());
                                tradeData.setLifecycleShutdownPeriod(response.getData().getLifecycle_shutdown_period());
                                tradeData.setPackageOrder(order);

                                /*组装数据返回*/
                                ResponseQueryDeviceRealTimeData data = new ResponseQueryDeviceRealTimeData();
                                data.setConnSeqNo(ConnSeqNo);
                                data.setPartnerCode(partnerCode);
                                data.setToken(token);
                                data.setTradeType(tradeType);
                                data.setTradeTime(curtime);
                                data.setTradeRstCode(1000);
                                data.setTradeRstMessage("success");
                                data.setTradeData(tradeData);

                                ResponseQueryDeviceRealTime deviceRealTime = new ResponseQueryDeviceRealTime();
                                deviceRealTime.setData(data);
                                deviceRealTime.setSign(MD5.calcMD5(JSON.toJSONString(data)));
                                // 返回给调用者的报文
                                jsonString = JSON.toJSONString(deviceRealTime);
                                log.info("响应报文：" + jsonString);
                                return jsonString;
                            }

                        }
                    }
                }
            }
        }
    }
}

